// src/router/generateRoutes.js
import componentMap from '@/utils/componentMap' // 导入组件映射表

/**
 * 递归处理后端路由数组，将 component 字符串转换为 Vue 组件模块
 * @param {Array<Object>} backendRoutes - 后端返回的路由数组 (或其 children 数组)
 * @returns {Array<Object>} - Vue Router 格式的路由数组
 */
function generateRoutesFromBackend(backendRoutes) {
  const resultRoutes = []

  if (!Array.isArray(backendRoutes)) {
    console.error(
      '[Dynamic Router] Invalid backend routes format: Not an array.'
    )
    return []
  }

  backendRoutes.forEach((route) => {
    if (!route || typeof route !== 'object') {
      console.warn('[Dynamic Router] Skipping invalid route object:', route)
      return // 跳过无效对象
    }

    const routerRoute = {
      path: route.path,
      name: route.name,
      meta: route.meta || {},
    }

    // === 处理 component 字段 ===
    if (route.component) {
      const mappedComponent = componentMap[route.component]
      if (mappedComponent) {
        routerRoute.component = mappedComponent
      } else {
        console.error(
          `[Dynamic Router] Component mapping not found for '${route.component}' in route: ${route.path}.`
        )
        // 如果组件映射找不到，通常跳过此路由，或者指向一个默认错误组件
        return
      }
    } else {
      // 如果后端没有 component，但有 children 且不是 redirect，假定它是 Layout
      if (route.children && !route.redirect) {
        const layoutComponent = componentMap['layout'] // 约定 Layout 用 'layout' 标识
        if (layoutComponent) {
          routerRoute.component = layoutComponent
        } else {
          console.error(
            `[Dynamic Router] Layout component mapping not found for parent route: ${route.path}. Skipping.`
          )
          return
        }
      } else if (!route.redirect) {
        // 如果既没有 component 也没有 children 也没有 redirect，跳过
        console.warn(
          `[Dynamic Router] Route ${route.path} has no component, children, or redirect. Skipping.`
        )
        return
      }
    }

    // === 处理 redirect 字段 ===
    if (route.redirect) {
      routerRoute.redirect = route.redirect
    }

    // === 递归处理子路由 ===
    if (
      route.children &&
      Array.isArray(route.children) &&
      route.children.length > 0
    ) {
      routerRoute.children = generateRoutesFromBackend(route.children)
      // 过滤掉无效的子路由
      routerRoute.children = routerRoute.children.filter(
        (child) => child && (child.component !== undefined || child.redirect)
      )
      // 如果父路由本身没有组件/重定向，且没有有效子路由，则跳过父路由
      if (
        routerRoute.children.length === 0 &&
        !routerRoute.component &&
        !routerRoute.redirect
      ) {
        console.warn(
          `[Dynamic Router] Parent route ${route.path} has no component/redirect and no valid children. Skipping.`
        )
        return
      }
    }

    // 将处理好的路由对象添加到结果数组
    resultRoutes.push(routerRoute)
  })

  return resultRoutes
}

export default generateRoutesFromBackend
